<?php
/**
 * twitter api connection abstraction class
 *
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
final class twitter_api_connection extends api_connection {
    protected $user_credentials = NULL;
    protected $connection = NULL;
    protected $user = NULL;
    protected $authorize_url = '';

    public function set_user_credentials($user_credentials) {
        $this->user_credentials = $user_credentials;
    }

    public function connect_and_verify() {
        if ($this->user_credentials == NULL) {
            throw new model_exception('User credentials are not set!');
        }

        try {
            $server_credentials = server_credentials::create_from_id(
              $this->user_credentials->get('server_credentials_id')
            );
        }
        catch (model_exception $e) {
            try {
                $server_credentials = server_credentials::get_newest();
            }
            catch (model_exception $e) {
                throw new error(
                  'Error: Requested server credentials do not exists!'
                );
            }
        }

        $this->connection =  new TwitterOAuth(
          $server_credentials->get_key(),
          $server_credentials->get_secret(),
          $this->user_credentials->get('access_token'),
          $this->user_credentials->get('access_token_secret')
        );

        $this->set_user();
    }

    protected function rate_limit_status_ok() {
        $status = $this->connection->get('account/rate_limit_status');
        
        return (
          $status->remaining_hits >= config::get('api', 'min_remaining_hits')
        );
    }

    protected function get($request, $parameters=NULL) {
        if (is_a($this->connection, 'TwitterOAuth')) {
            if ($this->rate_limit_status_ok()) {
                return $this->connection->get($request, $parameters);
            }
            else {
                throw new error('Error: Rate limit exceeded.');
            }
        }
        else {
            throw new error('Error: Connection to Twitter API failed.');
        }
    }

    public function set_user() {
        $this->user = $this->get('account/verify_credentials');

        if (!$this->request_successful()) {
            throw new error(
              'Error: Supplied user credentials are invalid.'
            );
        }
    }

    public function get_user_id() {
        return $this->user->id_str;
    }

    public function get_user_name() {
        return $this->user->name;
    }

    public function get_user_screen_name() {
        return $this->user->screen_name;
    }

    public function get_ff_ids() {
        $followers = $this->get('followers/ids');
        $friends = $this->get('friends/ids');

        return array_values(array_intersect($followers->ids, $friends->ids));
    }

    public function request_successful() {
        return ($this->connection->http_code == 200);
    }

    public function get_request_token() {
        $server_credentials = server_credentials::get_newest();

        $this->connection = new TwitterOAuth(
          $server_credentials->get_key(),
          $server_credentials->get_secret()
        );

        $request_token = $this->connection->getRequestToken(
          'https://pc-10329-virt10.ethz.ch/twitter/callback'
        );

        $this->authorize_url = $this->connection->getAuthorizeURL(
          $request_token['oauth_token']
        );

        return $request_token;
    }

    public function get_authorize_url() {
        if ($this->authorize_url == '') {
            throw new model_exception(
              'Authorize URL not set. Get request token first!'
            );
        }

        return $this->authorize_url;
    }

    public function get_access_token(
      $request_token,
      $request_token_secret,
      $oauth_verifier
    ) {
        $server_credentials = server_credentials::get_newest();

        $this->connection = new TwitterOAuth(
          $server_credentials->get_key(),
          $server_credentials->get_secret(),
          $request_token,
          $request_token_secret
        );

        $access_token = $this->connection->getAccessToken($oauth_verifier);

        if (!$this->request_successful()) {
            throw new model_exception('Cannot fetch access token!');
        }

        return $access_token;
    }
}
?>